<template>
	<view class="recruitingCraftsmen">
		<view class="gongshi flex_ac" @click="$wanlshop.to('/pages/craftsman/details?me=true&id='+data.id)">
			<image class="touxiang" v-if="data.images && data.images[0]" :src="$wanlshop.oss(data.images[0])" mode="">
			</image>
			<view class="ml24 flex1 overflow_1">

				<view class="flex_ac">
					<u-icon v-if="data.work_type == 1" name="https://img.aibbyp.com/wechatUser/jiazhuang.png"
						size="60"></u-icon>
					<u-icon v-if="data.work_type == 2" name="https://img.aibbyp.com/wechatUser/gongzhuang.png"
						size="60"></u-icon>
					<view class="f32 fb ml12">
						{{data.title}}
					</view>
					<u-tag v-if="data.type == 1" class="ml12" text="整装" size="mini" mode="plain" />
					<u-tag v-if="data.type == 2" class="ml12" text="局部改造" size="mini" mode="plain" />
					<u-tag v-if="data.type == 3" class="ml12" text="维修" size="mini" mode="plain" />


				</view>
				<view class="flex mt18 c3d f28 overflow_1 minwidth">
					<view class="flex1 minwidth f24 ">
						<view class=" overflow_1">
							<u-icon name="map" color="#FD5241" size="28"></u-icon>
							<text class="ml16 f28 c3d">
								{{data.address}}
							</text>
						</view>
						<view class="mt12">
							<u-icon name="clock" color="#FD5241" size="28"></u-icon>
							<text class="ml16 f28 c3d">
								{{data.start_date_text}} ~ {{data.end_date_text}}
							</text>
						</view>

					</view>
				</view>
			</view>
		</view>

		<view class="gongshi flex_ac mt32">
			<view class="f28 fb">
				招募时间
			</view>

			<view class="flex1 flex_ac tar f28 fb" @click="showCalendar = true">
				<view class="flex1 tar">
					{{times}}
				</view>
				<u-icon class="ml12" name="https://img.aibbyp.com/wechatUser/craftsman/arrow-down.png"
					size="44"></u-icon>
			</view>
		</view>
		<view class="listBoxs mt32">
			<view class="listForbox mb32" v-for="(item,key) in list" :key="key">
				<view class="flex_sb">
					<view class=" primary fb f32">
						工种{{key+1}}
					</view>
					<view class="info f28" @click="liseDelete(item,key)" v-if="list.length !== 1">
						删除
					</view>
				</view>
				<view class="flex_sb flex_ac border_botttom mt32">
					<text class="error mr12">*</text>
					<view class="mr24">
						工种类型
					</view>
					<u-input class="flex1" v-model="item.work_type_idsname" type="select" placeholder="请选择工种类型"
						@click="inputSelect('worker_type_id',key)" />
				</view>
				<view class="flex_sb flex_ac border_botttom mt32">
					<text class="error mr12">*</text>
					<view class="mr24">
						工种人数
					</view>
					<u-input class="flex1" @input="inputPrice(item,key)" maxlength="8" v-model="item.number"
						type="number" placeholder="请输入工种人数" />
					<view class="">
						名
					</view>
				</view>
				<view class="flex_sb flex_ac border_botttom mt32">
					<text class="error mr12">*</text>
					<view class="mr24 flex_ac">
						工人单价 <u-icon @click="grdjyh" size="32" class="pl12 pr8"
							name="https://img.aibbyp.com/wechatUser/yh.png"></u-icon>
					</view>
					<u-input class="flex1" @input="inputPrice(item,key)" v-model="item.price" maxlength="8" type="digit"
						placeholder="请输入工人单价" />
					<view class="">
						元
					</view>
				</view>
				<view class="flex_sb flex_ac mt32 mb32">
					<view class="mr24">
						<text class="error mr12">*</text>
						工种要求
					</view>
				</view>
				<u-input class="mt24" style="width: 100%;" v-model="item.demand" border height='60' type="textarea"
					placeholder="请输入工种要求" />
				<view class="tar mt32">
					工种价：<text class="cf64 fb">￥{{item.totalPrice}}</text>
				</view>
			</view>
			<view class="fb tac mt32 primary" @click="listPush">
				<u-icon name="plus" class="mr24"></u-icon> 添加工种
			</view>
		</view>
		<!-- https://img.aibbyp.com/wechatUser/craftsman/gzbj.png -->
		<view class="bottomBtn">
			<view class="fbts tac">
				发布成功后无法修改信息，需修改请取消订单，金额原路退回
			</view>
			<view class="flex flex_ac btns">
				<view class="cf64">
					总价 <text class="f32 fb">￥{{allPrice}}</text>
				</view>
				<view class="ml24">
					<u-button type="primary" shape='circle' @click="submit">支付并发布招募</u-button>
				</view>
			</view>
		</view>

		<u-calendar max-date='2050' :min-date='minData()' :max-date="data.end_date_text" v-model="showCalendar"
			mode="range" @change="changeCalendar"></u-calendar>
		<u-popup border-radius="30" v-model="showPopup" mode='bottom'>
			<view class="BoxPopup">
				<view class="flex_ac">
					<view class="f32 fb c3d flex1 tac ml12">
						选择工种类型
					</view>
					<view @click="showPopup=false">
						<u-icon name="close" size="30"></u-icon>
					</view>
				</view>
				<scroll-view scroll-y="true" style="height: 95%;">
					<u-checkbox-group @change="checkboxGroupChange" wrap max='1'>
						<u-checkbox size="50" label-size='40' v-model="item.checked" v-for="(item, index) in selectList"
							:key="index" :name="item.id">
							<view class="tar mt12">
								{{item.name}}
							</view>
						</u-checkbox>
					</u-checkbox-group>
				</scroll-view>
				<view class="mt32 flex_ac">
					<view class="flex1 ">
						<u-button type="error" @click="showPopup=false">确定选择</u-button>
					</view>
				</view>
			</view>
		</u-popup>

	</view>
</template>

<script>
	export default {
		data() {
			return {

				data: {},
				totalPrice: 0,
				times: '请选择时间',
				showCalendar: false,
				startDate: null,
				showPopup: false,
				endDate: null,
				allPrice: 0,
				list: [{
					number: '',
					price: '',
					demand: '',
					worker_type_id: '',
					work_type_idsname: '',
					totalPrice: 0,
				}],
				selectList: [],

				listIndex: 0,
			}
		},
		onLoad(option) {
			this.getWorkerTypeList()
			this.orderDetail(option.id)
		},
		methods: {

			submit() {
				if (!this.startDate || !this.endDate) {
					return this.$wanlshop.msg('请选择招募时间')
				}
				// 初始化验证状态为true
				let isValid = true;
				let workers = []
				// 遍历列表中的每个对象
				for (let i of this.list) {
					// 遍历对象的每个属性
					for (let k in i) {
						// 打印属性名和属性值（调试用）
						console.log(k, i[k]);

						// 如果属性值为空、空字符串或0（根据业务需求调整判断条件）
						if (!i[k] && i[k] !== 0) { // 注意：这里排除了数字0的情况，如果你希望0也算有效值
							isValid = false;
							// 一旦发现无效值，可以选择提前退出循环
							break;
						}
					}

					// 如果内层循环中发现无效值，也退出外层循环
					if (!isValid) break;
				}

				// 根据验证结果执行不同操作
				if (isValid) {
					console.log('所有字段都有值，可以发送接口');
					// 这里调用发送接口的函数
					this.$api.post({
						url: '/worker/recruit/addRecruit',
						data: {
							order_id: this.data.id,
							start_date: this.startDate,
							end_date: this.endDate,
							workers: this.list,
						},

					}).then(res => {
						res.forEach(a => {
							a.order_id = a.id,
								a.price = a.order_price
						})
						this.$wanlshop.to('/pages/user/money/pay?craftsman=1&data=' + JSON.stringify(res))
					})
				} else {
					console.log('存在空字段，不发送接口');
					// 可以在这里添加提示用户的逻辑
					this.$wanlshop.msg('请完整填写工种信息')
				}

				return isValid;
			},
			orderDetail(id) {
				this.$api.post({
					url: '/worker/task/orderDetail',
					data: {
						order_id: id
					},
				}).then(res => {
					this.data = res
				})
			},
			grdjyh() {
				uni.showModal({
					title: '提示',
					showCancel: false,
					content: '工人单价是按人头计算，公司需要结合施工天数计算单个师傅施工的总价钱， 并填入，平台会自动根据招募人数计算出总价',
					success: function(res) {
						if (res.confirm) {
							console.log('用户点击确定');
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			minData() {
				const today = new Date();

				// 获取年、月、日（注意月份需要 +1）
				const year = today.getFullYear();
				const month = String(today.getMonth() + 1).padStart(2, '0'); // 补零操作
				const day = String(today.getDate()).padStart(2, '0');

				// 拼接成目标格式
				const formattedDate = `${year}-${month}-${day}`;
				return formattedDate
			},
			inputPrice(item, key) { //计算价格
				if (item.number && item.price) {
					this.$set(this.list, key, {
						...this.list[key], // 保留原有属性
						totalPrice: this.$wanlshop.bcmul(item.number, item.price) // 更新 age 属性
					});

					this.allPrice = 0
					for (let i of this.list) {
						this.allPrice = this.$wanlshop.bcadd(i.totalPrice, this.allPrice)
					}
				} else {
					this.$set(this.list, key, {
						...this.list[key], // 保留原有属性
						totalPrice: 0 // 更新 age 属性
					});
					this.allPrice = 0
					for (let i of this.list) {
						this.allPrice = this.$wanlshop.bcadd(i.totalPrice, this.allPrice)
					}
				}
			},
			liseDelete(item, key) {
				this.list.splice(key, 1)
			},
			listPush() {
				this.list.push({
					number: '',
					price: '',
					demand: '',
					worker_type_id: '',
				})
			},
			getWorkerTypeList() {
				this.$api.get({
					url: '/worker/user/workerTypeList',
				}).then(res => {
					res.forEach(a => {
						a.checked = false
					})
					this.selectList = res

				})
			},
			inputSelect(type, key) {
				this.listIndex = key
				this.selectType = type
				this.selectList.forEach(a => {
					a.checked = false
				})
				this.showPopup = true
			},
			changeCalendar(e) {
				console.log(e);
				this.times = `${e.startDate}~${e.endDate}`
				this.startDate = e.startDate
				this.endDate = e.endDate
			},
			confirmSelect(i) {
				this.list[this.listIndex].work_type_idsname = i[0].label
				this.list[this.listIndex][this.selectType] = i[0].value
			},
			checkboxGroupChange(i) {

				this.list[this.listIndex].worker_type_id = i.join(',')
				let worker_type_id = []
				this.selectList.forEach(a => {
					i.forEach(b => {
						if (a.id == b) {
							worker_type_id.push(a.name)
						}
					})
				})
				this.list[this.listIndex].work_type_idsname = worker_type_id.join(',')

			},
			checkedAll() {
				if (this.list[this.listIndex].worker_type_id.length !== this.selectList.map(a => a.id).join(',').length) {
					console.log(this.list[this.listIndex].worker_type_id);
					this.list[this.listIndex].worker_type_id = this.selectList.map(a => a.id).join(',')
					this.selectList.map(val => {
						val.checked = true;
					})
				} else {
					this.list[this.listIndex].worker_type_id = ''
					this.selectList.map(val => {
						val.checked = false;
					})
				}

			},
		}
	}
</script>

<style lang="scss" scoped>
	.BoxPopup {

		// padding-bottom: env(safe-area-inset-bottom);
		padding: 40rpx 60rpx 140rpx;
		height: 70vh;
		overflow: hidden;

		.quxuan {
			width: 120rpx;
			height: 60rpx;
			text-align: center;
			margin: 0;
			padding: 0;
			font-size: 24rpx;
			margin-bottom: 20rpx;
		}
	}

	.recruitingCraftsmen {
		padding: 44rpx 32rpx 224rpx;
		width: 100%;
		background-image: url('https://img.aibbyp.com/wechatUser/craftsman/asdas.png');
		background-size: 750rpx 942rpx;
		background-repeat: no-repeat;
		display: flex;
		flex-direction: column;
		align-items: center;
		height: 100vh;
		overflow: scroll;

		.bottomBtn {
			z-index: 2;
			position: fixed;
			bottom: 0;
			width: 100%;

			.btns {
				padding: 32rpx 20rpx 40rpx;
				background: #fff;
				justify-content: flex-end;
			}

			.fbts {
				font-size: 24rpx;
				color: #3583F0;
				background: #E9F0FC;
			}
		}

		.border_botttom {
			border-bottom: 2rpx #eee solid;
			padding-bottom: 10rpx;
		}

		.listBoxs {
			width: 100%;
		}

		.listForbox {
			background-image: url('https://img.aibbyp.com/wechatUser/craftsman/gzbj.png');
			background-size: 186rpx 56rpx;
			background-repeat: no-repeat;
			background-color: #FFFFFF;
			border-radius: 20rpx 20rpx 20rpx 20rpx;
			width: 100%;
			padding: 10rpx 40rpx 32rpx 40rpx;
		}

		.tags {
			background: #E9F0FC;
			border-radius: 8rpx 8rpx 8rpx 8rpx;
			padding: 4rpx 10rpx;
			margin-right: 8rpx;
			font-size: 20rpx;
			white-space: nowrap;
		}

		.gongshi {
			width: 100%;
			background: #FFFFFF;
			border-radius: 8rpx 8rpx 8rpx 8rpx;
			padding: 24rpx 32rpx;

			.touxiang {
				width: 148rpx;
				height: 148rpx;
				border-radius: 5rpx 5rpx 5rpx 5rpx;
			}
		}
	}
</style>